//
// Created by francklinson on 2021/10/12 AT 10:29.
//
#include <iostream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#include <functional>
#include <climits>
#include <string>

using namespace std;

class Solution {
public:
    bool isAlienSorted(vector<string> &words, string order) {
        unordered_map<char, int> charMap;
        for (int i = 0; i < 26; ++i) {
            charMap[order[i]] = i;
        }
        for (int i = 0; i < words.size() - 1; ++i) {
//            if (!help1(words[i], words[i + 1], order))
//                return false;
            if (!help2(words[i], words[i + 1], charMap))
                return false;
        }
        return true;
    }

    bool help1(string &word1, string &word2, string &order) {
        auto m = word1.size(), n = word2.size();
        int i = 0;
        while (i < m and i < n) {
            if (word1[i] == word2[i]) {
                ++i;
                continue;
            } else {
                return order.find(word1[i]) < order.find(word2[i]);
            }
        }
        return m <= n;
    }

    bool help2(string &word1, string &word2, unordered_map<char, int> &um) {
        auto m = word1.size(), n = word2.size();
        int i = 0;
        while (i < m and i < n) {
            if (word1[i] == word2[i]) {
                ++i;
                continue;
            } else {
                return um[word1[i]] < um[word2[i]];
            }
        }
        return m <= n;
    }
};

int main() {
    Solution solution;
    vector<string> words{"word", "world", "row"};
    string order = "worldabcefghijkmnpqstuvxyz";
    cout << solution.isAlienSorted(words, order) << endl;
    return 0;
}

